﻿using System.Web;
using CxRomos.Core.Domain.Entities;
using StructureMap;

namespace CxRomos.Core.Services.Implementation {
    [Pluggable("Default")]
    public class WebContext : IWebContext {
        public string CaptchaImageText {
            get {
                return ContainsInSession("CaptchaImageText") ? GetFromSession("CaptchaImageText").ToString() : null;
            }
            set { SetInSession("CaptchaImageText", value); }
        }

        public Account CurrentUser {
            get {
                if (ContainsInSession("CurrentUser")) {
                    return GetFromSession("CurrentUser") as Account;
                }
                return null;
            }
            set { SetInSession("CurrentUser", value); }
        }

        public string Username {
            get {
                return ContainsInSession("Username") ? GetFromSession("Username").ToString() : "";
            }
            set { SetInSession("Username", value); }
        }

        public bool LoggedIn {
            get {
                if (ContainsInSession("LoggedIn")) {
                    return (bool)GetFromSession("LoggedIn");
                }
                return false;
            }
            set { SetInSession("LoggedIn", value); }
        }

        public string UsernameToVerify {
            get { return GetQueryStringValue("a").ToString(); }
        }

        public void ClearSession() {
            HttpContext.Current.Session.Clear();
        }

        public bool ContainsInSession(string key) {
            return HttpContext.Current.Session[key] != null;
        }

        public void RemoveFromSession(string key) {
            HttpContext.Current.Session.Remove(key);
        }

        private static string GetQueryStringValue(string key) {
            return HttpContext.Current.Request.QueryString.Get(key);
        }

        private static void SetInSession(string key, object value) {
            if (HttpContext.Current == null || HttpContext.Current.Session == null) {
                return;
            }
            HttpContext.Current.Session[key] = value;
        }

        private static object GetFromSession(string key) {
            if (HttpContext.Current == null || HttpContext.Current.Session == null) {
                return null;
            }
            return HttpContext.Current.Session[key];
        }

        private void UpdateInSession(string key, object value) {
            HttpContext.Current.Session[key] = value;
        }
    }
}